<?php
class Model{
	private $table;//表名
	private $options=array(
		'where'=>'',
		'limit'=>'',
		'order'=>'',
		'group'=>'',
		'having'=>''
	);
	public function __construct($table){
		$this->table = $table;
		$this->connect();
	}
	/**
	 * 连接数据库
	 * @return void
	 */
	private function connect(){
		mysql_connect(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD')) or halt('数据库连接错误');
		mysql_select_db(C('DB_NAME'));
		mysql_query("SET NAMES ".C('DB_CHARSET'));
	}
	//WHERE条件
	public function where($sql){
		$this->options['where']=" WHERE ".$sql;
		return $this;
	}
	//LIMIT条件
	public function limit($sql){
		$this->options['limit']=" LIMIT ".$sql;
		return $this;
	}
	//ORDER条件
	public function order($sql){
		$this->options['order']=" ORDER BY  ".$sql;
		return $this;
	}
	/**
	 * 查询结果集
	 * @return [type] [description]
	 */
	public function all(){
		$sql ="SELECT * FROM ".$this->table.
		$this->options['where'].
		$this->options['group'].
		$this->options['having'].
		$this->options['order'].
		$this->options['limit'];
		echo $sql;
		return $this->query($sql);
	}
	/**
	 * 插入数据
	 * @param array $data 要写入表的数据
	 */
	public function add($data){
		//只操作数组
		if(!is_array($data))return false;
		//INSERT INTO TABLE () VALUES();
		$field = implode(',',array_keys($data));
		$values =implode("','",array_values($data));
		$sql = 'INSERT INTO '.$this->table
		."(".$field.") VALUES('".$values."')";
		// echo $sql;
		return $this->exe($sql);
	}

	/**
	 * 针对增、删、改的操作
	 * @param  [type] $sql [description]
	 * @return [type]      [description]
	 */
	public function exe($sql)
	{
		if(mysql_query($sql)){
                  return mysql_insert_id()?mysql_insert_id():mysql_affected_rows();
		}else{
			halt(mysql_error());
		}
	}
	/**
	 * 获得有结果集的查询
	 * @param  [type] $sql sql语句
	 * @return array
	 */
	public function query($sql){
		if($result = mysql_query($sql)){
			$row=array();
			while($d = mysql_fetch_assoc($result)){
				$row[]=$d;
			}
			return $row;
		}else{
			return false;
		}
	}
}